<template>
  <view class="workFormViewer-wrap">
    <!-- 主表表单内容（为空时不渲染） -->
    <tm-sheet v-if="primaryTabsTitle.length > 0" :padding="[0]" :margin="[0]">
      <tm-tabs
        :list="primaryTabsTitle"
        align="left"
        :default-name="primaryFormsId"
        :active-name="primaryFormsId"
        activeColor="primary"
        activeFontColor="primary"
        _class="text-weight-b"
        @change="tabkey => tabChanged('primary', tabkey)"
      >
      </tm-tabs>
      <PrimaryForm v-if="selectPrimaryForm" :formInfo="selectPrimaryForm" />
    </tm-sheet>
    <!-- 子表表单详情 -->
    <tm-sheet v-if="detailTabsTitle.length > 0" :padding="[10]" :margin="[0]">
      <tm-tabs
        :list="detailTabsTitle"
        align="left"
        :default-name="detailFormsId"
        :active-name="detailFormsId"
        activeColor="primary"
        activeFontColor="primary"
        _class="text-weight-b"
        @change="tabKey => tabChanged('detail', tabKey)"
      >
      </tm-tabs>
      <DetailForm v-if="selectDetailForm" :key="detailFormsId" :formInfo="selectDetailForm" />
    </tm-sheet>
  </view>
</template>
<script lang="ts" setup>
import { inject, computed, Ref, ref } from 'vue'
import { CustomFormType } from '../../workTypes'
import PrimaryForm from './primaryForm.vue'
import DetailForm from './detailForm.vue'
import { watchEffect } from 'vue'

const detailForms = inject<Ref<CustomFormType[]>>(
  'detailForms',
  computed(() => [])
)
const primaryForms = inject<Ref<CustomFormType[]>>(
  'primaryForms',
  computed(() => [])
)

const primaryTabsTitle = computed(() =>
  primaryForms.value.map(item => {
    return { key: item.id, title: item.name }
  })
)
const detailTabsTitle = computed(() =>
  detailForms.value.map(item => {
    return { key: item.id, title: item.name }
  })
)
//当前选中的主表/子表id
console.log('primaryForms',primaryForms)
let primaryFormsId = ref<string>('')
// const primaryFormsId:any = ''

const detailFormsId = ref<string>('')
const selectPrimaryForm = computed(() =>
  primaryForms.value.find(item => item.id === primaryFormsId.value)
)
const selectDetailForm = computed(() =>
  detailForms.value.find(item => item.id === detailFormsId.value)
)

watchEffect(() => {
  if (primaryFormsId.value === '' && primaryForms.value.length > 0) {
    primaryFormsId.value = primaryForms.value[0].id
  }
  if (detailFormsId.value === '' && detailForms.value.length > 0) {
    detailFormsId.value = detailForms.value[0].id
  }
})
function tabChanged(type: 'primary' | 'detail', tabKey: string) {
  if (type === 'primary') {
    primaryFormsId.value = tabKey
  } else {
    detailFormsId.value = tabKey
  }
}
</script>

<style lang="scss" scoped>
.workFormViewer-wrap {
  display: flex;
  flex-direction: column;
  height: 100%;
}
</style>
